package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"time"
)

var redis_url = "127.0.0.1:6379"

// go get github.com/garyburd/redigo/redis
func main() {
	//testStringStructure()
	//testHashStructure()
	testListStructure()
}

// testStringStructure
//
//	@Description: string结构
func testStringStructure() {
	//连接redis服务器
	conn, err := redis.Dial("tcp", redis_url)
	if err != nil {
		fmt.Println("redis conn err=", err)
	}
	//设置值
	r, err := conn.Do("Set", "name", "jerry-cat")
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}
	rV := r.(string)
	fmt.Println("操作", rV) //OK

	//获取值
	v, err := redis.String(conn.Do("Get", "name"))
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}
	fmt.Println(v)

	//删除值
	r1, err := conn.Do("Del", "name")
	fmt.Println("操作", r1) //1
	//获取值
	v, err = redis.String(conn.Do("Get", "name"))
	if err != nil {
		fmt.Println("conn.Do err=", err) //conn.Do err= redigo: nil returned
	}
	fmt.Println(v)

	//设置过期时间
	r, err = conn.Do("Set", "k1", "v2")
	_, err = conn.Do("expire", "k1", 100)
	ttl, err := conn.Do("ttl", "k1")
	fmt.Println(ttl)
	time.Sleep(time.Second * 5)
	ttl, err = conn.Do("ttl", "k1")
	fmt.Println(ttl)

}

// testHashStructure
//
//	@Description: hash结构
func testHashStructure() {
	conn, err := redis.Dial("tcp", redis_url)
	if err != nil {
		fmt.Println("redis conn err=", err)
	}
	_, err = conn.Do("HSet", "user01", "name", "tom")
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}
	_, err = conn.Do("HSet", "user01", "age", 18)
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}
	name, err := redis.String(conn.Do("HGet", "user01", "name"))
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}
	fmt.Printf("%T %v", name, name)

	_, err = conn.Do("HDel", "user01", "name")
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}
	name, err = redis.String(conn.Do("HGet", "user01", "name"))
	if err != nil {
		fmt.Println("conn.Do err=", err) //string tomconn.Do err= redigo: nil returned
	}
	fmt.Printf("%T %v", name, name)
}

// testListStructure
//
//	@Description: list结构
func testListStructure() {

	conn, err := redis.Dial("tcp", redis_url)
	if err != nil {
		fmt.Println("redis conn err=", err)
	}
	conn.Do("lpush", "list01", "v1", "v2", "v3")
	v, err := redis.Strings(conn.Do("lrange", "list01", 0, -1))
	if err != nil {
		fmt.Println("conn.Do err=", err)
	}

	fmt.Println(v)
}

// testRedisPool
//
//	@Description: 测试pool
func testRedisPool() {
	var pool *redis.Pool = &redis.Pool{
		MaxIdle:     8,   //最大空闲连接数
		MaxActive:   0,   //最大连接数，0-表示没有限制
		IdleTimeout: 300, //最大空闲时间
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", "localhost:6379")
		},
	}
	conn := pool.Get()
	defer conn.Close()
	s, err := redis.String(conn.Do("Get", "w1"))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%T %v", s, s)
}
